class Page < ActiveRecord::Base
	has_one									:graphic, :dependent => :destroy
	has_many								:comments, :dependent => :destroy
	belongs_to 							:section
	has_and_belongs_to_many	:datasheets
	belongs_to              :user
	
	validates_presence_of 	:section_id, :name, :state
	validates_uniqueness_of :name
	
	# This method is a override to display the name of the object in the URL.
	# Before:  	http://root/page/1
	# After:		http://root/page/1-solutions
	def to_param
    "#{id}-#{name.downcase.gsub(/[^[:alnum:]]/,'-')}".gsub(/-{2,}/,'-')   
  end
	
	def self.home_pages
		find(:all, :conditions => ["home = ?", true])
	end
		
	def self.pending_pages
		find(:all, :conditions => ["state = ?", "pending"], :order => "updated_at ASC")
	end
	
	def my_comments
	  	self.comments.find(:all, :conditions => ["updated_at >= ?", Time.now - 7.days], :order => "updated_at DESC")
  end
	
	def set_published
	  self.state = "published"
  end
  
  def set_pending
    self.state = "pending"
  end
  
  def set_draft
    self.state = "draft"  
  end
  
  def is_home?
    self.home == true
  end

	def published?
		self.state == "published"
	end
  
	def owner
    self.user
	end
	
	def owner_full_name
		self.user.full_name
	end
	
	def self.recent_pages
	  find(:all, :conditions => ["updated_at >= ?", Time.now - 7.days], :order => "updated_at DESC")
  end
  
  # Gets the home page for a section
  def self.home_page(section)
    find(:first, :include => :section, :conditions => ["home = ? and sections.name = ?", true, section])
  end
  
  # Gets all the non-home page pages for a section
  def self.sub_pages(section)
    find(:all, :include => :section, :conditions => ["home = ? and sections.name = ?", false, section])
  end
  
  def send_email(type, url_name)
 
    if type == "reject"
      email=Notifier.create_reject_message(self,url_name)
    elsif type == "edit"
      email =Notifier.create_edit_message(self,url_name)
    elsif type == "pending"
      email=Notifier.create_pending_review_message(User.publisher_emails, url_name, self)
    end
    
    email.set_content_type("text/html")
    Notifier.deliver(email)
  end
  
  # Checks to see is an instance of Page is part of the News section. 
  def news?
    self.section_id == Section.find_by_name("news").id
  end
  
  def self.all_news
    find(:all, :conditions => [ "section_id = ?", Section.find_by_name("news").id ], :order => "created_at DESC")
  end
     
end